package com.sikaryofficial.backend.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sikaryofficial.backend.domain.entity.UserReportLog;
import com.sikaryofficial.backend.mapper.UserReportLogMapper;
import com.sikaryofficial.backend.service.IUserReportLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 举报日志Service业务层处理
 *
 * @author qinjinyuan
 * @date 2023-11-11
 */
@Service
public class UserReportLogServiceImpl extends ServiceImpl<UserReportLogMapper, UserReportLog> implements IUserReportLogService {
    @Autowired
    private UserReportLogMapper reportLogMapper;

    @Override
    public List<UserReportLog> getLogByReportId(List<Long> reportIds) {
        if (CollUtil.isEmpty(reportIds)) {
            return Collections.emptyList();
        }
        return this.list(new LambdaQueryWrapper<UserReportLog>()
                .in(UserReportLog::getReportId, reportIds)
                .eq(UserReportLog::getDeletedVersion, 0L)
        );
    }

    @Override
    public Map<Long, Optional<UserReportLog>> getLatestLogByReportId(List<Long> reportIds) {
        List<UserReportLog> reportLogs = getLogByReportId(reportIds);
        // 使用流根据reportId分组，并找到每个组中的最大元素（最新记录）
        return reportLogs.stream()
                .collect(Collectors.groupingBy(UserReportLog::getReportId,
                        Collectors.maxBy(Comparator.comparing(UserReportLog::getCreatedTime))));
    }
}
